package {
	import flash.events.*;
	import flash.geom.*;
	import flash.media.*;
	import flash.net.*;
	import flash.utils.*;
	
	import mx.collections.ArrayCollection;
	import mx.core.*;
	
	public class Level {
		protected static var instance:Level = null;
		// Background elements
		protected static const TimeBetweenLevelElements:Number = 2;
		protected var timeToNextLevelElement:Number = 0;
		protected var levelElementGraphics:ArrayCollection = new ArrayCollection();
		// Player
		protected static var player:Player;
		// Enemies
		protected var timeToNextEnemy:Number = 0;
		protected var enemyElementGraphics:ArrayCollection = new ArrayCollection();
		protected static const TimeBetweenEnemies:Number = 3;		
		// Music
		protected var backgroundMusic:SoundChannel = null;
		
					
		static public function get Instance():Level {
			if ( instance == null ) instance = new Level();
			return instance;
		}
		
		public function Level(caller:Function = null ) {
			if ( Level.instance != null ) throw new Error( "Only one Singleton instance should be instantiated" );
			
			levelElementGraphics.addItem(ResourceManager.IroningBoardGraphics );		
			levelElementGraphics.addItem(ResourceManager.ChainsawGraphics );		
			enemyElementGraphics.addItem(ResourceManager.NormGraphics);
			
		}
		
		public function startup():void {
			timeToNextLevelElement = 0;
			player = new Player();
			player.startup();
			backgroundMusic = ResourceManager.Track1FX.play(0, int.MAX_VALUE);			
		}
		
		public function getScore():Number {
			return player.getScore();
		}
		
		public function shutdown():void {
			backgroundMusic.stop();
			backgroundMusic = null;
		}
		
		public function enterFrame(dt:Number):void	{
			
			// Add a background element
			timeToNextLevelElement -= dt;
			if (timeToNextLevelElement <= 0) {
				timeToNextLevelElement = TimeBetweenLevelElements;
				var graphics:GraphicsResource = levelElementGraphics.getItemAt(Math.floor(Math.random()* levelElementGraphics.length)) as GraphicsResource;
				var backgroundLevelElement:BackgroundLevelElement = BackgroundLevelElement.pool.ItemFromPool as BackgroundLevelElement;
				backgroundLevelElement.startupBackgroundLevelElement( graphics, new Point(Math.random() * Application.application.width, -graphics.bitmap.height), ZOrder.BackgoundZOrder, 50);
			}
			
			// Add an enemy
			timeToNextEnemy -= dt;			
			if (timeToNextEnemy <= 0) {
				timeToNextEnemy = TimeBetweenEnemies;
				var enemygraphics:GraphicsResource = enemyElementGraphics.getItemAt( Math.floor( Math.random() * enemyElementGraphics.length)) as GraphicsResource;
				var enemy:Enemy = Enemy.pool.ItemFromPool as Enemy;
				enemy.startupBasicEnemy(
					enemygraphics,
					new Point(Math.random() * Application.application.width, -enemygraphics.bitmap.height),
					50 + Math.random()*20);
			}
		}
	}
}

